<script setup lang="tsx">
import type { DataTableColumns, FormInst } from 'naive-ui'
import { useBoolean } from '@/hooks'
import { adminApi } from '@/service/api/bizhi'
import { NButton, NPopconfirm, NSpace, NSwitch, NTag } from 'naive-ui'
import TableModal from './components/TableModal.vue'

const { bool: loading, setTrue: startLoading, setFalse: endLoading } = useBoolean(false)

const initialModel = {
  username: '',
  role: '',
  is_active: '',
}
const model = ref({ ...initialModel })
function handleResetSearch() {
  model.value = { ...initialModel }
  getAdminList()
}

// 搜索功能
function handleSearch() {
  getAdminList()
}

const formRef = ref<FormInst | null>()
const modalRef = ref()

// 删除管理员
async function deleteAdmin(id: number) {
  try {
    const response = await adminApi.deleteAdmin(id)
    if (response.code === 200) {
      window.$message.success('管理员删除成功')
      getAdminList()
    }
  } catch (error: any) {
    window.$message.error(error?.response?.data?.message || '删除失败')
  }
}

interface AdminData {
  id: number
  username: string
  email: string
  phone: string
  real_name?: string
  role: 'super_admin' | 'admin'
  is_active: boolean
  created_at: string
  last_login_at?: string
}

const columns: DataTableColumns<AdminData> = [
  {
    title: 'ID',
    align: 'center',
    key: 'id',
    width: 80,
  },
  {
    title: '用户名',
    align: 'center',
    key: 'username',
  },
  {
    title: '真实姓名',
    align: 'center',
    key: 'real_name',
    render: (row) => row.real_name || '-',
  },
  {
    title: '邮箱',
    align: 'center',
    key: 'email',
  },
  {
    title: '手机号',
    align: 'center',
    key: 'phone',
  },
  {
    title: '角色',
    align: 'center',
    key: 'role',
    render: (row) => {
      const tagType = row.role === 'super_admin' ? 'error' : 'primary'
      const roleText = row.role === 'super_admin' ? '超级管理员' : '普通管理员'
      return (
        <NTag type={tagType}>
          {roleText}
        </NTag>
      )
    },
  },
  {
    title: '状态',
    align: 'center',
    key: 'is_active',
    render: (row) => {
      return (
        <NSwitch
          value={row.is_active}
          onUpdateValue={(value: boolean) =>
            handleUpdateStatus(value, row.id)}
        >
          {{ checked: () => '启用', unchecked: () => '禁用' }}
        </NSwitch>
      )
    },
  },
  {
    title: '创建时间',
    align: 'center',
    key: 'created_at',
    render: (row) => new Date(row.created_at).toLocaleDateString(),
  },
  {
    title: '操作',
    align: 'center',
    key: 'actions',
    render: (row) => {
      return (
        <NSpace justify="center">
          <NButton
            size="small"
            onClick={() => modalRef.value.openModal('edit', row)}
          >
            编辑
          </NButton>
          <NPopconfirm onPositiveClick={() => deleteAdmin(row.id)}>
            {{
              default: () => '确认删除该管理员？',
              trigger: () => <NButton size="small" type="error">删除</NButton>,
            }}
          </NPopconfirm>
        </NSpace>
      )
    },
  },
]

const count = ref(0)
const listData = ref<AdminData[]>([])

// 更新管理员状态
async function handleUpdateStatus(value: boolean, id: number) {
  try {
    const response = await adminApi.updateStatus({
      admin_id: id,
      is_active: value
    })
    if (response.code === 200) {
      window.$message.success('状态更新成功')
      // 更新本地数据
      const index = listData.value.findIndex(item => item.id === id)
      if (index > -1) {
        listData.value[index].is_active = value
      }
    }
  } catch (error: any) {
    window.$message.error(error?.response?.data?.message || '状态更新失败')
    // 恢复原状态
    const index = listData.value.findIndex(item => item.id === id)
    if (index > -1) {
      listData.value[index].is_active = !value
    }
  }
}

// 获取管理员列表
async function getAdminList() {
  startLoading()
  try {
    const params: any = {
      page: 1,
      limit: 20
    }

    // 添加搜索条件
    if (model.value.username) params.username = model.value.username
    if (model.value.role) params.role = model.value.role
    if (model.value.is_active !== '') params.is_active = model.value.is_active

    const response = await adminApi.getAdminList(params)
    if (response.code === 200) {
      listData.value = response.data.list
      count.value = response.data.pagination.total
    }
  } catch (error: any) {
    window.$message.error(error?.response?.data?.message || '获取管理员列表失败')
  } finally {
    endLoading()
  }
}

onMounted(() => {
  getAdminList()
})

function changePage(page: number, size: number) {
  // TODO: 实现分页逻辑
  window.$message.info(`切换到第${page}页，每页${size}条`)
}

// 角色选项
const roleOptions = [
  { label: '全部角色', value: '' },
  { label: '超级管理员', value: 'super_admin' },
  { label: '普通管理员', value: 'admin' }
]

// 状态选项
const statusOptions = [
  { label: '全部状态', value: '' },
  { label: '启用', value: 'true' },
  { label: '禁用', value: 'false' }
]
</script>

<template>
  <div class="admin-management">
    <NSpace vertical>
      <!-- 搜索表单 -->
      <n-card>
        <n-form ref="formRef" :model="model" label-placement="left" inline :show-feedback="false">
          <n-flex>
            <n-form-item label="用户名" path="username">
              <n-input v-model:value="model.username" placeholder="请输入用户名" clearable />
            </n-form-item>
            <n-form-item label="角色" path="role">
              <n-select
                v-model:value="model.role"
                :options="roleOptions"
                placeholder="请选择角色"
                clearable
                class="w-150px"
              />
            </n-form-item>
            <n-form-item label="状态" path="is_active">
              <n-select
                v-model:value="model.is_active"
                :options="statusOptions"
                placeholder="请选择状态"
                clearable
                class="w-150px"
              />
            </n-form-item>
            <n-flex class="ml-auto">
              <NButton type="primary" @click="handleSearch">
                <template #icon>
                  <icon-park-outline-search />
                </template>
                搜索
              </NButton>
              <NButton strong secondary @click="handleResetSearch">
                <template #icon>
                  <icon-park-outline-redo />
                </template>
                重置
              </NButton>
            </n-flex>
          </n-flex>
        </n-form>
      </n-card>

      <!-- 数据表格 -->
      <n-card class="flex-1">
        <template #header>
          <NButton type="primary" @click="modalRef.openModal('add')">
            <template #icon>
              <icon-park-outline-add-one />
            </template>
            新建管理员
          </NButton>
        </template>
        <NSpace vertical>
          <n-data-table :columns="columns" :data="listData" :loading="loading" />
          <Pagination :count="count" @change="changePage" />
        </NSpace>

        <TableModal ref="modalRef" modal-name="管理员" @refresh="getAdminList" />
      </n-card>
    </NSpace>
  </div>
</template>

<style scoped>
.admin-management {
  padding: 20px;
}

.w-150px {
  width: 150px;
}
</style>
